package com.px.pa.modulars.circle.controller;


import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.px.basic.alone.security.annotation.Inner;
import com.px.basic.alone.security.util.SecurityUtils;
import com.px.pa.modulars.circle.entity.CircleOrganizational;
import com.px.pa.modulars.circle.service.CircleOrganizationalService;
import com.px.pa.modulars.circle.service.ConversionTaskService;
import com.px.pa.modulars.upms.entity.SysUser;
import com.px.pa.modulars.upms.service.SysUserService;
import com.px.plugins.conversion.core.entity.ConversionTaskEntity;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/import")
public class importExcelFormController {


    @Autowired
    private CircleOrganizationalService circleOrganizationalService;


    @Value("${export-path.user-form}")
    private String path;


    @Autowired
    private ConversionTaskService conversionTaskService;

    @Autowired
    private SysUserService sysUserService;
    private SysUser getUser(){
        SysUser user = sysUserService.getById(SecurityUtils.getUser().getId());
        return user;
    }
    /*
        导出定义好的表单
     */
    @RequestMapping("/export")
    public void export(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        String path = "F:/data/协会人员信息普查表.xls";

        ExcelWriter ew = ExcelUtil.getWriter(path);
        List<String> strList = new ArrayList<>();

        List<CircleOrganizational> list = circleOrganizationalService.list(new QueryWrapper<CircleOrganizational>()
                .eq("tenant_code",getUser().getOnlyLogo())
                .ne("parent_id", 0)
                .orderByAsc("sort"));
        list.forEach(a -> {
            strList.add(a.getName());
        });
        String[] array = strList.toArray(new String[strList.size()]);

        CellRangeAddressList addressList = new CellRangeAddressList(3, 3, 1, 1);

        DataValidationHelper helper = ew.getSheet().getDataValidationHelper();

        DataValidationConstraint constraint = helper.createExplicitListConstraint(array);

        DataValidation validation = helper.createValidation(constraint, addressList);

        ew.addSelect(1, 3, array);

        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=template.xls");

        ServletOutputStream out = response.getOutputStream();

        if (validation instanceof XSSFDataValidation) {
            validation.setSuppressDropDownArrow(true);
            validation.setShowErrorBox(true);
        } else {
            validation.setSuppressDropDownArrow(false);
        }

        ew.flush(out, true);

        ew.close();
        IoUtil.close(out);
    }

    /*
       根据文件所在路径下载文件
        */
    @RequestMapping("/download")
    @Inner(value = false)
    public void download(HttpServletRequest request, HttpServletResponse response) {
        String filePath = request.getParameter("path");
        File file = new File(filePath);
        // 取得文件名。
        String fileName = file.getName();
        InputStream fis = null;
        try {
            fis = new FileInputStream(file);
            request.setCharacterEncoding("UTF-8");
            String agent = request.getHeader("User-Agent").toUpperCase();
            if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))
                fileName = URLEncoder.encode(fileName, "UTF-8");
            else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            }
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("Content-Length", String.valueOf(file.length()));

            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
                response.getOutputStream().write(b, 0, len);
            }
            response.flushBuffer();
            fis.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/conversionTaskPage")
    public R ConversionTaskList(Page page) {
        Integer uid = SecurityUtils.getUser().getId();
        return R.ok(conversionTaskService.page(page, new QueryWrapper<ConversionTaskEntity>().
                eq("create_by", uid)
                .orderByDesc("start_time")));
    }


}
